package com.rgst.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.rgst.cons.Cons;
import com.rgst.dto.UserDto;

/**
 * Created by tancw on 2019/11/21.
 */
public class BaseController {

    public boolean noSession(HttpServletRequest request) {
        return request.getSession().getAttribute(Cons.SESSION_USER) == null;
    }

    public UserDto getSessionUser(HttpServletRequest request) {
        return (UserDto) request.getSession().getAttribute(Cons.SESSION_USER);
    }

    public void setSessionUser(HttpServletRequest request, UserDto userDto) {
        request.getSession().setAttribute(Cons.SESSION_USER, userDto);
    }

    @ExceptionHandler
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception exception) {
        ModelAndView view = new ModelAndView();
        view.setViewName("error");
        if(exception instanceof BindException){
            String message = ((BindException) exception).getAllErrors().get(0).getDefaultMessage();
            view.addObject("message",message);
        }
        return view;
    }
}
